package handlers

// 绑定，解绑
import (
	"cron-go/configs/error_code"
	"cron-go/internal/pkg/crontab/dao"
	"cron-go/internal/pkg/crontab/models"
	"cron-go/internal/pkg/crontab/task"
	"fmt"

	"github.com/go-liam/util/conv"
	"github.com/go-liam/util/response"
)

type BindCrontab struct {
	Req  *BindCrontabReq
	IDs  []int64
	Data interface{}
}

type BindCrontabReq struct {
	IDs    []string `json:"ids" validate:"required" ` // crontab
	Status int      `json:"status"  `                 // 1 bind,0 remove
}

func (s *BindCrontab) GetData() *response.APIResponse {
	s.Change()
	if len(s.IDs) == 0 {
		return &response.APIResponse{Code: error_code.RequestParameter, Message: error_code.MsRequest, Data: ""}
	}
	s.Bind()
	return &response.APIResponse{Code: error_code.Success, Message: error_code.MsSuccess, Data: s.Data}
}

func (s *BindCrontab) Change() {
	s.IDs = conv.ArrayStringToInt64(s.Req.IDs)
}

func (s *BindCrontab) Bind() {
	page := &response.Pagination{PageSize: 50000, Current: 1}
	where := fmt.Sprintf(" and id in (%v) ", conv.ArrayToString(s.IDs, ","))
	r := &response.ListParameter{WhereSt: where, OrderSt: " order by id "}
	ls, _ := new(dao.TaskDao).FindMulti(page, r)
	//bind
	baseModels := make([]*models.TaskMysqlModel, 0)
	for _, item := range ls {
		i := new(models.TaskMysqlModel)
		i.ID = item.ID
		i.Spec = item.Spec
		baseModels = append(baseModels, i)
	}
	if s.Req.Status == 1 {
		task.Service.BatchAdd(baseModels)
	} else {
		task.Service.BatchRemove(baseModels)
		s.Req.Status = 0
	}
	//update
	data := make(map[string]interface{})
	num, err := new(dao.TaskDao).UpdateStatus(s.IDs, s.Req.Status)
	data["rowsAffected"] = num
	data["error"] = err
	s.Data = data
}
